<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" label-width="120px">
      <el-form-item label="集团名称" prop="company">
        <el-input v-model="dataForm.company" placeholder="集团名称"></el-input>
      </el-form-item>
      <el-form-item label="集团账号" prop="account">
        <el-input v-model="dataForm.account" placeholder="集团账号" :disabled="editFlag"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="pic">
        <el-upload class="avatar-uploader" :action="picUploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" width="250" />
          <el-icon v-else class="el-icon--upload" style="width: 200px; height: 50px"><upload-filled /></el-icon>
          <div style="color: red">建议png透明底图片,尺寸288*100</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="企业类型" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选类型">
          <el-option v-for="item in dict.type" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="集团编码">
        <el-input v-model="dataForm.companyCode" placeholder="集团编码"></el-input>
      </el-form-item>
      <!--      <el-form-item label="老师数量" prop="type">
        <el-input v-model="dataForm.teacherNum" placeholder="老师数量 "></el-input>
      </el-form-item>
      <el-form-item label="学生数量" prop="type">
        <el-input v-model="dataForm.studentNum" placeholder="学生数量"></el-input>
      </el-form-item>-->
      <el-form-item label="税号" prop="taxNo">
        <el-input v-model="dataForm.taxNo" placeholder="税号"></el-input>
      </el-form-item>
      <!--      <el-form-item label="省份" prop="type">
        <el-select v-model="dataForm.provinceCode" placeholder="请选省份" @change="selectCity()">
          <el-option v-for="item in dict.provinceCode" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="type">
        <el-select v-model="dataForm.cityCode" placeholder="请选城市">
          <el-option v-for="item in dict.cityCode" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="地址"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="dataForm.contacts" placeholder="联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系人电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="联系人电话"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="mail">
        <el-input v-model="dataForm.mail" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="私域空间(M)" prop="spaceSize">
        <el-input-number v-model="dataForm.spaceSize" placeholder="私域空间大小（M）" max="100000000"></el-input-number>
      </el-form-item>
      <el-form-item label="到期时间" prop="dueDate">
        <el-date-picker v-model="dataForm.dueDate" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择到期时间"> </el-date-picker>
      </el-form-item>

      <!--      <el-form-item label="创建时间" prop="createAt">
        <el-input v-model="dataForm.createAt" placeholder="创建时间"></el-input>
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input v-model="dataForm.creator" placeholder="创建人"></el-input>
      </el-form-item>
      <el-form-item label="修改时间" prop="updateAt">
        <el-input v-model="dataForm.updateAt" placeholder="修改时间"></el-input>
      </el-form-item>
      <el-form-item label="修改人" prop="updator">
        <el-input v-model="dataForm.updator" placeholder="修改人"></el-input>
      </el-form-item>-->
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive } from "vue";
import baseService from "@/service/baseService";
import { useDebounce } from "@/utils/utils";
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
export default defineComponent({
  setup() {
    const validatePhone = (rule: any, value: string, callback: any) => {
      if (!value) {
        return callback(new Error("号码不能为空!!"));
      }
      const phoneReg = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/;
      const isMob1 = /0\d{2,3}\d{7,8}/; //不带-的座机：02985111752
      const isMob2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/; //带一个-：029-85111752
      const isMob3 = /^\d{3,4}-\d{3,4}-\d{3,4}$/; //带三个-： 0752-250-520
      setTimeout(() => {
        if (!phoneReg.test(value) && !isMob1.test(value) && !isMob2.test(value) && !isMob3.test(value)) {
          callback(new Error("格式有误"));
        } else {
          callback();
        }
      }, 100);
    };
    /**
     * 校验邮箱
     * @param rule
     * @param value
     * @param callback
     */
    const validMail = (rule: any, value: string, callback: any) => {
      const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
      if (!value) {
        return callback(new Error("邮箱不能为空!!"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入合法的邮箱"));
      } else {
        callback();
      }
    };

    return reactive({
      visible: false,
      editFlag: false,
      picUploadUrl: "",
      dict: {
        type: baseService.strDict("1:连锁企业,2:独立学校")
      },
      dataForm: {
        id: "",
        company: "",
        account: "",
        pic: "",
        companyCode: "",
        teacherNum: "",
        studentNum: "",
        type: "",
        taxNo: "",
        //cityCode: "",
        // provinceCode: "",
        address: "",
        contacts: "",
        phone: "",
        mail: "",
        spaceSize: "",
        createAt: "",
        creator: "",
        updateAt: "",
        updator: "",
        dueDate: ""
      },
      dataRule: {
        company: [
          { required: true, message: "请输入集团名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        pic: [{ required: true, message: "请上传头像", trigger: "blur" }],
        type: [{ required: true, message: "请选择类企业类型", trigger: "change" }],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          { min: 2, max: 80, message: "长度在 2 到 80 个字符", trigger: "blur" }
        ],
        companyCode: [
          { required: true, message: "请输入企业编码", trigger: "blur" },
          { min: 4, max: 6, message: "长度在4 到 6 个字符", trigger: "blur" }
        ],
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 4, max: 16, message: "长度在4 到 16 个字符", trigger: "blur" }
        ],
        dueDate: [{ required: true, message: "请输入到期时间", trigger: "blur" }],
        phone: [{ validator: validatePhone, message: "请输入正确格式的电话", trigger: "blur" }],
        mail: [{ validator: validMail, message: "请输入正确格式的邮箱", trigger: "blur" }]
      }
    });
  },
  computed: {
    dataRule() {
      return {};
    }
  },
  created() {
    this.dataFormSubmitHandle = useDebounce(this.dataFormSubmitHandle);
    this.picUploadUrl = `${app.api}/sys/oss/upload?token=${getToken()}`;
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataFormRef"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
          this.editFlag = true;
        } else {
          this.editFlag = false;
        }
      });
    },
    handleAvatarSuccess(res: IObject, file: IObject) {
      this.dataForm.pic = res.data.src;
    },
    beforeAvatarUpload(file: IObject) {
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        this.$message.error("只支持jpg、png、gif格式的图片！");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isLt2M;
    },
    // 获取信息
    getInfo() {
      baseService.get("/fii/fiicompany/" + this.dataForm.id).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = res.data;
      });
    },
    // 表单提交
    dataFormSubmitHandle() {
      this.$refs["dataFormRef"].validate((valid: boolean) => {
        if (!valid) {
          return false;
        }
        (!this.dataForm.id ? baseService.post : baseService.put)("/fii/fiicompany", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
        });
      });
    }
  }
});
</script>
